package com.egobuy.search.dao.impl;

import com.egobuy.entity.Item;
import com.egobuy.pojo.EgoBuyPager;
import com.egobuy.search.dao.SearchDAO;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.rest.RestStatus;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Repository;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
/**
 * @author Hello
 */
@Repository
public class SearchDAOImpl implements SearchDAO {
    @Autowired
    private RestHighLevelClient client; //ES的客户端

    @Value("${indexName}")
    private String indexName;
    @Override
    public boolean insertOrUpdate(Map map) {
        //添加索引
        IndexRequest request=new IndexRequest(indexName);
        request.source(map);
        try {
            IndexResponse response = client.index(request, RequestOptions.DEFAULT);
            return response.status()== RestStatus.CREATED;
        } catch (IOException e) {
            e.printStackTrace();
            throw  new RuntimeException(e.getMessage());
        }

    }

    @Override
    public EgoBuyPager<Item> search(String keyWord, int page, int size) {
        //搜素
        EgoBuyPager<Item> pager=new EgoBuyPager<>();
        pager.setCurrent(page);
        pager.setSize(size);
        //查询
        SearchRequest searchRequest=new SearchRequest(indexName);
        //
        SearchSourceBuilder sourceBuilder=new SearchSourceBuilder();
        sourceBuilder.query(QueryBuilders.matchQuery("title",keyWord));
        //设置高亮显示
        HighlightBuilder highlightBuilder=new HighlightBuilder();
        highlightBuilder.preTags("<font color='red'>");
        highlightBuilder.postTags("</font>");
        highlightBuilder.field("title");
        sourceBuilder.highlighter(highlightBuilder);

        //
        sourceBuilder.from((page-1)*size);
        sourceBuilder.size(size);
        searchRequest.source(sourceBuilder);

        try {
            SearchResponse response = client.search(searchRequest, RequestOptions.DEFAULT);
            // 取出总条数
            long total = response.getHits().getTotalHits().value;
            // 计算最大页码
            int maxPageNum = (int)Math.ceil(total*1.0/size);
            pager.setPages(maxPageNum);
            pager.setTotal(total);
            // 处理数据
            List<Item> items = new ArrayList<>();
            SearchHits hits = response.getHits();
            Iterator<SearchHit> iterator = hits.iterator();
            while(iterator.hasNext()){
                SearchHit hit = iterator.next();
                Item item = new Item();
                Map<String, Object> map = hit.getSourceAsMap();
                item.setId(new Long(map.get("id").toString()));
                item.setTitle(map.get("title").toString());
                item.setSellPoint(map.get("sellPoint").toString());
                item.setPrice(new Long(map.get("price").toString()));
                // 图片处理
                Object imageObj = map.get("image");
                String image = imageObj!=null ? imageObj.toString().split(";")[0]:"";
                item.setImage(image);
                items.add(item);
            }
            pager.setRecords(items);
            System.out.println(response);

        } catch (IOException e) {
            e.printStackTrace();
            throw new RuntimeException(e.getMessage());
        }


        return pager;
    }

    @Override
    public boolean insertOrUpdate(Item item) {
        // 添加索引
        IndexRequest request = new IndexRequest(indexName);
        request.id(item.getId().toString());
        request.source("id", item.getId().toString(), "title", item.getTitle(), "sellPoint", item.getSellPoint(),
                "image", item.getImage(), "price", item.getPrice());
        try {
            IndexResponse response = client.index(request, RequestOptions.DEFAULT);
            return response.status() == RestStatus.CREATED;
        } catch (IOException e) {
            e.printStackTrace();
            throw new RuntimeException(e.getMessage());
        }
    }
}
